package com.mornd.gulimall.order.web.v1;

import com.alipay.api.AlipayApiException;
import com.mornd.gulimall.common.core.exception.ServiceException;
import com.mornd.gulimall.order.config.pay.AliPay;
import com.mornd.gulimall.order.config.pay.AlipayTemplate;
import com.mornd.gulimall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author: mornd
 * @dateTime: 2023/8/28 - 8:35
 * 订单支付
 */

@Slf4j
@Controller
public class PayController {
    @Resource
    private AlipayTemplate alipayTemplate;
    @Resource
    private IOrderService orderService;

    @ResponseBody
    @GetMapping(value = "/payOrder", produces = "text/html")
    public String payOrder(@RequestParam("orderSn") String orderSn) {
        AliPay aliPay = orderService.getPayInfo(orderSn);

        if (aliPay == null) {
            throw new ServiceException("该订单不存在");
        }

        String form = "";
        try {
            form = alipayTemplate.pay(aliPay);
        } catch (AlipayApiException e) {
            log.error(e.getErrMsg());
            throw new ServiceException("支付异常，请稍候重试");
        }
        return form;

//        httpResponse.setContentType("text/html;charset=utf-8");
//        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
    }

}
